<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css">


  <meta name="keywords" content="android,源码,listview,PinnedHead,HeaderView,">








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2">






<meta name="description" content="####本系列博客主要用于学习开源源码中一些优秀的编码思想技巧和一些不常见的开发方式。  千里之行，始于足下  ####明确学习意图首先明确学习研究PinnedHeaderListView这个源码的用途，通过阅读本博客你可以了解到以下几个方面：(约定如下：官方的是HeaderView，自己定义的header叫pinnedHeaderView)  如何去监听ListView，如何知道当前可见的ite">
<meta name="keywords" content="android,源码,listview,PinnedHead,HeaderView">
<meta property="og:type" content="article">
<meta property="og:title" content="拆解PinnedHeaderListView源码">
<meta property="og:url" content="http://guohaiyang.tk/post/c411cb4b.html">
<meta property="og:site_name" content="Android探索之路">
<meta property="og:description" content="####本系列博客主要用于学习开源源码中一些优秀的编码思想技巧和一些不常见的开发方式。  千里之行，始于足下  ####明确学习意图首先明确学习研究PinnedHeaderListView这个源码的用途，通过阅读本博客你可以了解到以下几个方面：(约定如下：官方的是HeaderView，自己定义的header叫pinnedHeaderView)  如何去监听ListView，如何知道当前可见的ite">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-12-26T17:44:13.294Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="拆解PinnedHeaderListView源码">
<meta name="twitter:description" content="####本系列博客主要用于学习开源源码中一些优秀的编码思想技巧和一些不常见的开发方式。  千里之行，始于足下  ####明确学习意图首先明确学习研究PinnedHeaderListView这个源码的用途，通过阅读本博客你可以了解到以下几个方面：(约定如下：官方的是HeaderView，自己定义的header叫pinnedHeaderView)  如何去监听ListView，如何知道当前可见的ite">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"hide","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键词进行搜索","hits_empty":"找不到有关『${query}』的文章，是不是去火星了？","hits_stats":"呼哧呼哧~~ 总于找到${hits} 篇文章，花了 ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://guohaiyang.tk/post/c411cb4b.html">





  <title>拆解PinnedHeaderListView源码 | Android探索之路</title>
  














</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <!-- 添加github fork me -->
    <a href="https://github.com/guohaiyang1992" rel="external nofollow noopener noreferrer" target="_blank"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Android探索之路</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">吾将上下而求索</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br>
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://guohaiyang.tk/post/c411cb4b.html">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="guohaiyang">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="http://avatar.csdn.net/E/A/A/1_guohaiyang1992.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Android探索之路">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">拆解PinnedHeaderListView源码</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-10-25T00:27:00+08:00">
                2016-10-25
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/源来如此/" itemprop="url" rel="index">
                    <span itemprop="name">源来如此</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/post/c411cb4b.html" class="leancloud_visitors" data-flag-title="拆解PinnedHeaderListView源码">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读热度</span>
               
                 <span class="leancloud-visitors-count"></span> ℃
             </span>
          

          

          
            <br>
            <div class="post-wordcount">
              
                <!--
                  <span class="post-meta-divider">|</span>
                -->
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计</span>
                
                <span title="字数统计">
                  1,647 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长</span>
                
                <span title="阅读时长">
                  7 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>####本系列博客主要用于学习开源源码中一些优秀的编码思想技巧和一些不常见的开发方式。</p>
<blockquote>
<p>千里之行，始于足下</p>
</blockquote>
<p>####明确学习意图<br>首先明确学习研究PinnedHeaderListView这个源码的用途，通过阅读本博客你可以了解到以下几个方面：(约定如下：官方的是HeaderView，自己定义的header叫pinnedHeaderView)</p>
<ol>
<li>如何去监听ListView，如何知道当前可见的item的位置，以及对其拓展的操作。</li>
<li>了解到ListView中的HeadView 和FooterView。</li>
<li>了解ViewGroup的绘制过程。</li>
<li>了解View的定位方法。</li>
<li>了解View的另类绘制方法。</li>
<li>了解PinnedHeaderListView的核心实现原理。<br>带着上面几方面的疑惑去看下面的源码分析或许能收获更多</li>
</ol>
<p>####首先通过对代码的解读，发现其比较重要的4个类</p>
<ul>
<li>PinnedHeaderListView: 实现组的头部总是悬浮在顶部的listview </li>
<li>SectionedBaseAdapter: 封装的adapter的抽象类 </li>
<li>PinnedHeaderListViewMainActivity: 具体使用的activity </li>
<li>TestSectionedAdapter: 实现了抽象类SectionedBaseAdapter的adapter</li>
</ul>
<p>####我们先来解读以下SectionedBaseAdapter<br>我们看到它实现了PinnedHeaderListView.PinnedSectionedHeaderAdapter  这个接口<br>其定义如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">public static interface PinnedSectionedHeaderAdapter &#123;</span><br><span class="line">    public boolean isSectionHeader(int position); //是否是组的头部</span><br><span class="line">    public int getSectionForPosition(int position); //根据位置判断对应的组号</span><br><span class="line">    public View getSectionHeaderView(int section, View convertView, ViewGroup parent); // 得到组的头部view</span><br><span class="line">     public int getSectionHeaderViewType(int section); </span><br><span class="line">     public int getCount();</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<p>比较重要的方法后面都有了对应的注释，源码中写的也比较简单，在次不再细说，主要是getSectionHeaderView方法比较重要，是我们获取headView的方法。此处不是我们研究的重点，感兴趣的可以去深入研究一下。</p>
<p>####下面我们来分析一下PinnedHeaderListView<br>我们看到它</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">public class PinnedHeaderListView extends ListView implements OnScrollListener , AdapterView.OnItemClickListener</span><br></pre></td></tr></table></figure>
<p>主要是OnScrollListener  这个是我们监听当前的Listview滚动状态的监听器。<br>我们先总体的看一下OnScroll里面的方法，代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line">@Override</span><br><span class="line">    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) &#123;</span><br><span class="line">        if (mOnScrollListener != null) &#123;</span><br><span class="line">            mOnScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);//使外部也可以监听到onScroll事件</span><br><span class="line">        &#125;</span><br><span class="line">        headerCount = getHeaderViewsCount();//获取headView</span><br><span class="line">        if (mAdapter == null || mAdapter.getCount() == 0 || !mShouldPin || (firstVisibleItem &lt; headerCount)) &#123;</span><br><span class="line">            mCurrentHeader = null;</span><br><span class="line">            mHeaderOffset = 0.0f;</span><br><span class="line">            for (int i = firstVisibleItem; i &lt; firstVisibleItem + visibleItemCount; i++) &#123;</span><br><span class="line">                View header = getChildAt(i);</span><br><span class="line">                if (header != null) &#123;</span><br><span class="line">                    header.setVisibility(VISIBLE);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            return;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        firstVisibleItem -= getHeaderViewsCount();//去掉header view的影响</span><br><span class="line"></span><br><span class="line">        int section = mAdapter.getSectionForPosition(firstVisibleItem); //得到组号</span><br><span class="line">        int viewType = mAdapter.getSectionHeaderViewType(section);</span><br><span class="line">        mCurrentHeader = getSectionHeaderView(section, mCurrentHeaderViewType != viewType ? null : mCurrentHeader);</span><br><span class="line">        //layout header,使它在最顶端</span><br><span class="line">        ensurePinnedHeaderLayout(mCurrentHeader);</span><br><span class="line">        mCurrentHeaderViewType = viewType;</span><br><span class="line">        mHeaderOffset = 0.0f;</span><br><span class="line">        for (int i = firstVisibleItem; i &lt; firstVisibleItem + visibleItemCount; i++) &#123;</span><br><span class="line">            if (mAdapter.isSectionHeader(i)) &#123;</span><br><span class="line">                View header = getChildAt(i - firstVisibleItem);</span><br><span class="line">                float headerTop = header.getTop();</span><br><span class="line">                float pinnedHeaderHeight = mCurrentHeader.getMeasuredHeight();</span><br><span class="line">                header.setVisibility(VISIBLE);</span><br><span class="line">                if (pinnedHeaderHeight &gt;= headerTop &amp;&amp; headerTop &gt; 0) &#123; // 下一个组的头部快滑动到顶部，距离顶部的距离小于现在在顶部悬浮的head的高度了</span><br><span class="line">                    mHeaderOffset = headerTop - header.getHeight(); //MheaderOffset是小于0的</span><br><span class="line">                &#125; else if (headerTop &lt;= 0) &#123; //下一个组的头部滑动到了顶部了</span><br><span class="line">                    header.setVisibility(INVISIBLE);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        invalidate();</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>此处的代码比较多，我们一点一点的进行分析。</p>
<h4 id="代码细节"><a href="#代码细节" class="headerlink" title="代码细节"></a>代码细节</h4><ul>
<li><strong>设置外部监听的回调</strong>：<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">if (mOnScrollListener != null) &#123;</span><br><span class="line">            mOnScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);//使外部也可以监听到onScroll事件</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>这段代码是让用户设置滑动监听的时候也能监听到对应的事件</p>
<ul>
<li><strong>获取Listview的HeaderView</strong><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">headerCount = getHeaderViewsCount(); //获取headView</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>首先我们得了解一下什么是headerView，怎么使用。<br>headview是通过listview.addHeaderView（）的方式添加的，此处可以添加的任何一种类型的view,而且此处的布局是不需要经过adpter也就是说不需要经过getView（）。<br>如果当你需要在Listview最上方设置一个布局且不需要它随着下面的数据的变动而改变使用此方法正合适。另一个与之对应的是addFooterView（）,这个就是加底部的布局的。</p>
<p>此方法是用于获取headerView的数量的，从而我们也就知道了，headerView是可以设置多个的。（headerview会影响onItemClickLisener方法中的position）</p>
<ul>
<li><strong>判断的符合条件</strong><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">if (mAdapter == null || mAdapter.getCount() == 0 || !mShouldPin || (firstVisibleItem &lt; headerCount)) &#123;</span><br><span class="line">                 ...</span><br><span class="line">                 return</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>如果满足了这些条件的话就直接return ，这些属于无效条件</p>
<ul>
<li><strong>得到分组相关的数据</strong></li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">firstVisibleItem -= getHeaderViewsCount();//去掉header view的影响</span><br><span class="line">int section = mAdapter.getSectionForPosition(firstVisibleItem); //得到组号</span><br><span class="line">int viewType = mAdapter.getSectionHeaderViewType(section);</span><br><span class="line">mCurrentHeader = getSectionHeaderView(section, mCurrentHeaderViewType != viewType ? null : mCurrentHeader);</span><br></pre></td></tr></table></figure>
<p>之前我们说过headerView会影响我们的position，影响的内容为getView中使用的postion和OnItemClickLisener中的postion不对应，所以我们需要消除headerView的影响，减去headerView的数量，就是其在getView中的位置</p>
<ul>
<li><strong>重置数据并使headerView一直在最上方</strong></li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ensurePinnedHeaderLayout(mCurrentHeader);//重新对mCurrentHeader定位，让其一直在最上方</span><br><span class="line">mCurrentHeaderViewType = viewType;</span><br><span class="line">mHeaderOffset = 0.0f;//移动的间距</span><br></pre></td></tr></table></figure>
<p>比较重要的方法就是ensurePinnedHeaderLayout（）我们稍后详细的分析它。</p>
<ul>
<li><strong>正真的核心代码</strong></li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">for (int i = firstVisibleItem; i &lt; firstVisibleItem + visibleItemCount; i++) &#123;</span><br><span class="line">        if (mAdapter.isSectionHeader(i)) &#123;</span><br><span class="line">            View header = getChildAt(i - firstVisibleItem);</span><br><span class="line">            float headerTop = header.getTop();</span><br><span class="line">            float pinnedHeaderHeight = mCurrentHeader.getMeasuredHeight();</span><br><span class="line">            header.setVisibility(VISIBLE);</span><br><span class="line">            if (pinnedHeaderHeight &gt;= headerTop &amp;&amp; headerTop &gt; 0) &#123; // 下一个组的头部快滑动到顶部，距离顶部的距离小于现在在顶部悬浮的head的高度了</span><br><span class="line">                mHeaderOffset = headerTop - header.getHeight(); //MheaderOffset是小于0的</span><br><span class="line">            &#125; else if (headerTop &lt;= 0) &#123; //下一个组的头部滑动到了顶部了</span><br><span class="line">                header.setVisibility(INVISIBLE);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>从整体上看，这是遍历可视范围内的item，然后通过<code>mAdapter.isSectionHeader(i)</code>判断是不是header,然后通过<code>getChildAt(i - firstVisibleItem)</code> 获取当前listview对应位置的布局，通过这两个判断同时成立的话就是获取当前最上方的pinnedHeaderView 。而mCurrentHeader 是上一个组的pinnedHeaderView ，通过<code>header.getTop()</code> 获取当前最上方的pinnedHeaderView 距离上方的位置，通过<code>mCurrentHeader.getMeasuredHeight()</code> 获取上一个pinnedHeaderView 的高度，通过<code>header.setVisibility(VISIBLE)</code>  恢复header的显示，这个是用于往回滚时的操作，与之对应的是<code>header.setVisibility(INVISIBLE)</code><br>我们先看一下这个判断条件<code>if (pinnedHeaderHeight &gt;= headerTop &amp;&amp; headerTop &gt; 0)</code>，当当前的mCurrentHeader高度大于当前最上方的pinnedHeaderView 的话说明此时下方已经和当前的mCurrentHeader将要交叉。通过<code>mHeaderOffset = headerTop - header.getHeight()</code> 获取偏移量<br>另一个判断<code>(headerTop &lt;= 0)</code> 这个是当当前的header划过顶部的时候，通过<code>header.setVisibility(INVISIBLE);</code>进行隐藏，所以我们也就知道了它正真的过程，是当划过的时候将其隐藏了，回来的时候又重新设置可见了，而上方的View又是怎么回事呢？我们来继续分析</p>
<p>####未完待续…</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/android/" <i="" class="fa fa-tag"> android</a>
          
            <a href="/tags/源码/" <i="" class="fa fa-tag"> 源码</a>
          
            <a href="/tags/listview/" <i="" class="fa fa-tag"> listview</a>
          
            <a href="/tags/PinnedHead/" <i="" class="fa fa-tag"> PinnedHead</a>
          
            <a href="/tags/HeaderView/" <i="" class="fa fa-tag"> HeaderView</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/post/276dec51.html" rel="next" title="Android技巧总结  系列一">
                <i class="fa fa-chevron-left"></i> Android技巧总结  系列一
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/post/39808cf6.html" rel="prev" title="AndroidEventBus教程">
                AndroidEventBus教程 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zMjczNS85Mjk2"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image" src="http://avatar.csdn.net/E/A/A/1_guohaiyang1992.jpg" alt="guohaiyang">
          <p class="site-author-name" itemprop="name">guohaiyang</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
           
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">31</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">10</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">71</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


        <!--外链播放器-->
        <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width="330" height="86" src="//music.163.com/outchain/player?type=2&id=504575633&auto=0&height=66"></iframe>

      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#代码细节"><span class="nav-number">1.</span> <span class="nav-text">代码细节</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">guohaiyang</span>
</div>
<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<!--<div class="powered-by"> -->
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  您是本站的第<span id="busuanzi_value_site_uv"></span>个访客，欢迎您的到来
</span>
<!--</div>-->

<!--屏蔽下方提示-->
<!--<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div> -->


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "db.json";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("h8Ih0Dm3ikBRV6HNGyvsiu8C-gzGzoHsz", "LWjl3Esuf1ArMkWbwcPbjGqV");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  

  

</body>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>
</html>

